<?php
namespace app\classes\util;


class MulPager {

    public static function page($params, $totalNum, $pageSize, $preLink)
    {
        $showRange = 2;     // 显示当前页数前后数量

        $sPage = '<div class="pagination"><ul><li class="prev-page">';
        $iCurPage = !empty($params['page']) ? $params['page'] : 1;
        $arParams = $params;

        if ($iCurPage > 1) {
            $preParams = $params;
            $preParams['page'] = $iCurPage - 1;
            $sPreLink = self::_buildUrl($preLink, $preParams);
            $sPage .= "<a href='{$sPreLink}'>上一页</a></li>";

        }

        $pageTotal = ceil($totalNum / $pageSize);

        $arParams['page'] = 1;
        $sPage .= self::_addPage(1, $iCurPage, self::_buildUrl($preLink, $arParams));
        if ($iCurPage > 2+$showRange) {
            $sPage .= "<li><span>...</span></li>";
        }

        $i = $iCurPage - 2 > 1 ? $iCurPage - 2: 2;
        for (; $i <= $pageTotal && $i <= $iCurPage+$showRange; $i++) {
            $arParams['page'] = $i;
            $sPage .= self::_addPage($i, $iCurPage, self::_buildUrl($preLink, $arParams));
        }

        if ($iCurPage+$showRange < $pageTotal) {
            $sPage .= "<li><span>...</span></li>";
        }

        if ($iCurPage < $pageTotal) {
            $preParams = $params;
            $preParams['page'] = $iCurPage + 1;
            $sPostLink = self::_buildUrl($preLink, $preParams);
            $sPage .= "<li class='next-page'><a href='{$sPostLink}'>下一页</a></li>";
        } else {
            $sPage .= "<li class='next-page'><a href='javascript:void(0)'>下一页</a></li>";
        }

        $sPage .= "</ul></div>";
        return $sPage;
    }

    public static function _buildUrl ($preLink, $params)
    {
        return 'http://' . $preLink . '?' . http_build_query($params);
    }

    private static function _addPage ($page, $iCurPage, $url)
    {
        $sPage = '';
        if ($page == $iCurPage) {
            $sPage .= "<li class='active'><a href='{$url}'>{$page}</a></li>";
        } else {
            $sPage .= "<li><a href='{$url}'>{$page}</a></li>";
        }
        return $sPage;
    }
}